class Magnifier {
    constructor(options) {
        //获取元素
        this.ele = document.querySelector(options)
        this.show = this.ele.querySelector('.show')
        this.mask = this.ele.querySelector('.mask')
        this.enlarge = this.ele.querySelector('.enlarge')
        this.picture = this.enlarge.firstElementChild

        //获取元素尺寸
        this.show_w = this.show.clientWidth
        this.show_h = this.show.clientHeight
        this.mask_w = parseInt(window.getComputedStyle(this.mask).width)
        this.mask_h = parseInt(window.getComputedStyle(this.mask).height)
        this.picture_w = parseInt(window.getComputedStyle(this.picture).width)
        this.picture_h = parseInt(window.getComputedStyle(this.picture).height)

        // 调用
        this.billie()
        this.overout()
        this.move()
    }

    //方法
    //计算比列
    billie() {
        /* 
               mask 尺寸          x（要求的值）
            ———————————————— = —————————————————    解析：mask * picture / show
               show 尺寸          picture 尺寸
        */
        this.enlarge_w = this.mask_w * this.picture_w / this.show_w
        this.enlarge_h = this.mask_h * this.picture_h / this.show_h

        // 赋值
        this.enlarge.style.width = this.enlarge_w + 'px'
        this.enlarge.style.height = this.enlarge_h + 'px'

    }




    // 鼠标移入移出
    overout() {
        // 鼠标移入
        this.show.addEventListener('mouseover', () => {
            this.mask.style.display = 'block'
            this.enlarge.style.display = 'block'
        })

        // 鼠标移出
        this.show.addEventListener('mouseout', () => {
            this.mask.style.display = 'none'
            this.enlarge.style.display = 'none'
        })
    }


    //移动
    move() {
        //给show盒子添加鼠标移动事件
        this.show.addEventListener('mousemove', (e) => {
            e = e || window.event
                //获取坐标值
            let x = e.offsetX - this.mask.clientWidth / 2
            let y = e.offsetY - this.mask.clientHeight / 2
                //设置边界值
                //左下
            if (x <= 0) x = 0
            if (y <= 0) y = 0
                //右上
            if (x >= this.show_w - this.mask_w) x = this.show_w - this.mask_w
            if (y >= this.show_h - this.mask_h) y = this.show_h - this.mask_h


            //赋值给 mask 盒子
            this.mask.style.left = x + 'px'
            this.mask.style.top = y + 'px'


            /*计算大图偏移量
                        mask 移动距离               mask 尺寸
                    ————————————————————  =   ————————————————————   解析：
                        大图移动距离 x             enlarge 尺寸
            */
            this.enlarge_x = x * this.enlarge_w / this.mask_w
            this.enlarge_y = y * this.enlarge_w / this.mask_w


            //进行赋值  让大盒子给随 mask（遮罩层）移动 
            this.picture.style.left = -this.enlarge_x + 'px'
            this.picture.style.top = -this.enlarge_y + 'px'


        })
    }
}